package com.snoob.lixing.exception;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA
 * User: lixing
 * Date: 2018/11/25 22:40
 * <p>
 * 自定义全局异常处理器（只能有一个）
 * 系统的dao、service、controller出现异常都通过throws Exception向上抛出，最后由SpringMVC前端控制器交由自定义全局异常处理器处理（跳转到错误页面）
 */
@Component
@ControllerAdvice
public class GlobalExceptionResolver implements HandlerExceptionResolver {
    /**
     * Try to resolve the given exception that got thrown during handler execution,
     * returning a {@link ModelAndView} that represents a specific error page if appropriate.
     * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty}
     * to indicate that the exception has been resolved successfully but that no view
     * should be rendered, for instance by setting a status code.
     *
     * @param request   current HTTP request
     * @param response  current HTTP response
     * @param handler   the executed handler, or {@code null} if none chosen at the
     *                  time of the exception (for example, if multipart resolution failed)
     * @param exception the exception that got thrown during handler execution
     * @return a corresponding {@code ModelAndView} to forward to,
     * or {@code null} for default processing in the resolution chain
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        String msg;
        if (exception instanceof CustomerException) {
            /**
             * 自定义异常
             */
            CustomerException custExp = (CustomerException) exception;
            msg = custExp.getExpMessage();
        } else {
            /**
             * 运行时异常
             */
            msg = "系统错误"; // msg = exception.getMessage();
        }

        //LoggerUtil.debug("=========================全局异常处理器捕获异常【START】");
        //LoggerUtil.debug(MessageFormat.format("异常信息:{0}", msg));
        //LoggerUtil.debug("=========================全局异常处理器捕获异常【END】");

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", msg);
        modelAndView.setViewName("error");
        return modelAndView;
    }
}
